package com.app.lxx.pregnancyberth.widge;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import androidx.core.content.FileProvider;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.lxx.pregnancyberth.R;
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;


public class UtilsManage {

    private Context mContext;

    public UtilsManage(Context context) {
        mContext = context;
    }

    private static Handler handler = new Handler();

    /**
     * 判断软键盘 弹出
     */
    public void showSoftInput(Context context) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive()) {
            inputMethodManager.toggleSoftInput(0, InputMethodManager.RESULT_SHOWN);
        }
    }

    /**
     * 关闭键盘的方法
     *
     * @param context
     * @param currentFocus
     */
    public void closeKeyBoardMethod(Context context, View currentFocus) {
//        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//        inputMethodManager.hideSoftInputFromWindow(OpeListActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        if (currentFocus != null) {
            ((InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(currentFocus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 测量View的宽高
     *
     * @param view View
     */
    public static void measureWidthAndHeight(View view) {
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 生成不重复随机数
     *
     * @param num
     * @param total
     * @return
     */
    public static ArrayList<Integer> numRandom(int num, int total) {
        Set<Integer> set = new LinkedHashSet<>();
        while (set.size() < num) {
            set.add((int) (Math.random() * total));
        }
        return new ArrayList<>(set);
    }

    /**
     * 从assert文件夹中获取json数据
     */
    public static String initJsonData(Context context, String fileName) {
        JSONObject jsonObject = null;
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = context.getAssets().open(fileName);//打开json数据
            byte[] by = new byte[is.available()];//转字节
            int len = -1;
            while ((len = is.read(by)) != -1) {
                sb.append(new String(by, 0, len, "UTF-8"));//根据字节长度设置编码
            }
            is.close();//关闭流
            jsonObject = new JSONObject(sb.toString());//为json赋值
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    public String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    //将图片字节流转换成base64字符串
    public static String bitmapStreamToBaseStringImg(Bitmap planImg) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Bitmap photodata = planImg;
            //将bitmap一字节流输出 Bitmap.CompressFormat.PNG 压缩格式，100：压缩率，baos：字节流
            photodata.compress(Bitmap.CompressFormat.PNG, 100, baos);
            baos.close();
            byte[] buffer = baos.toByteArray();
            //将图片的字节流数据加密成base64字符输出
            String photo = Base64.encodeToString(buffer, 0, buffer.length, Base64.DEFAULT);
            return photo;
        } catch (Exception e) {

        }
        return "";
    }

    private static Dialog dialog;
    private static String sitemTv;

    /**
     * dialog 属性
     *
     * @param localView
     * @return
     */
    public Dialog dialog(Activity activity, View localView, int gravity, boolean outSide) {
        Dialog dialog = new Dialog(activity, R.style.custom_dialog);
        dialog.setContentView(localView);
        dialog.setCanceledOnTouchOutside(outSide);
        dialog.getWindow().setGravity(gravity);
        WindowManager windowManager = activity.getWindowManager();// 设置全屏
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = display.getWidth(); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.show();
        return dialog;
    }

    /**
     * 滚轮选择
     *
     * @param activity
     * @param view
     * @param title    标题
     */
    public void showWheelViewDialog(Activity activity, final TextView view, String title, final List<String> mOptionsList) {
        sitemTv = mOptionsList.get(0);
        View localView = LayoutInflater.from(activity).inflate(R.layout.dialog_wheelview_select, null);
        dialog = dialog(activity, localView, Gravity.BOTTOM, true);
        ImageView recharge_dialog_cencle = localView.findViewById(R.id.dialog_cencle);
        Button recharge_dialog_submit = localView.findViewById(R.id.dialog_submit);
        TextView wheel_view_tv = localView.findViewById(R.id.wheel_view_tv);
        wheel_view_tv.setText(title);
        WheelView wheelView = localView.findViewById(R.id.wheelview);

        wheelView.setCyclic(false);
        wheelView.setTextSize(20);

        wheelView.setAdapter(new ArrayWheelAdapter(mOptionsList));
        wheelView.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                sitemTv = mOptionsList.get(index);
            }
        });

        recharge_dialog_cencle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        recharge_dialog_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view.setText(sitemTv);
                dialog.dismiss();
            }
        });
    }


    /**
     * RecyclerView到达底部的方法
     *
     * @param recyclerView
     * @return
     */
    public boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null)
            return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }


    public static void parseXMLWithPull(String xmlData) throws Exception {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(new StringReader(xmlData));
        int eventType = parser.getEventType();
        String name = "";
        String version = "";
        while (eventType != XmlPullParser.END_DOCUMENT) {
            String nodeName = parser.getName();
            switch (eventType) {
                // 开始解析某个结点
                case XmlPullParser.START_TAG: {
                    if ("p".equals(nodeName)) {
                        name = parser.nextText();
                    } else if ("img".equals(nodeName)) {
                        version = parser.nextText();
                    }
                    break;
                }
                // 完成解析某个结点
                case XmlPullParser.END_TAG: {
                    if ("p".equals(nodeName)) {
                        Log.d("MainActivity", "name is " + name);
                        Log.d("MainActivity", "version is " + version);
                    }
                    break;
                }
                default:
                    break;
            }
            eventType = parser.next();
        }
    }

    public GridLayoutManager gridLayoutManager(Context context, int spanCount, final int isTwoLine) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, spanCount);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (isTwoLine == 1) {
                    if (position == 0) {
                        return 2;
                    }
                    return 1;
                } else {
                    return 1;
                }
            }
        });

        return gridLayoutManager;
    }


    public GridLayoutManager gridLayoutManager(Context context, int spanCount, final boolean canScroll) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, spanCount) {
            @Override
            public boolean canScrollVertically() {
                return canScroll;
            }

            @Override
            public boolean canScrollHorizontally() {
                return super.canScrollHorizontally();
            }
        };
        return gridLayoutManager;
    }

    public LinearLayoutManager linearLayoutManager(Context context, int orientation, final boolean canScroll) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, orientation, false) {
            @Override
            public boolean canScrollVertically() {
                return canScroll;
            }
        };
        return linearLayoutManager;
    }

    public boolean isNull(HashMap<String, String> hashMap) {
        List<String> keys = new ArrayList<>(hashMap.keySet());
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = hashMap.get(key);
            if (TextUtils.isEmpty(value)) {
                // Toast.makeText(mContext, "信息不完整", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;
    }

    /**
     * 控制输入格式，保留小数位
     *
     * @param edt Editable
     */
    public void limitDecimalDigits(Editable edt, int digit) {
        if (edt == null) {
            return;
        }

        // 以小数点开头，前面自动加上 "0"
        if (edt.toString().startsWith(".")) {
            edt.insert(0, "0");
        }

        //只能输入一个小数点
        if (edt.toString().contains(".") && edt.toString().lastIndexOf(".") != edt.toString().indexOf(".")) {
            edt.delete(edt.toString().length() - 1, edt.toString().length());
        }

        //保留小数位
        int posDot = edt.toString().indexOf(".");
        if (posDot <= 0) {
            return;
        }
        if (edt.toString().length() - posDot - 1 > digit) {
            edt.delete(posDot + digit, posDot + digit + 1);
        }
    }


    /**
     * 获取网络图片
     *
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public Bitmap GetImageInputStream(String imageurl) {
        URL url;
        HttpURLConnection connection = null;
        Bitmap bitmap = null;
        try {
            url = new URL(imageurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    private void deleteImage() {
        File file = new File(Environment.getExternalStorageDirectory() + "/name/" + "/" + "图片名" + ".JPG");
        file.delete();
    }

    /**
     * 对字符串处理:将指定位置到指定位置的字符以星号代替
     *
     * @param content 传入的字符串
     * @param begin   开始位置
     * @param end     结束位置
     * @return
     */
    private String getStarString(String content, int begin, int end) {

        if (begin >= content.length() || begin < 0) {
            return content;
        }
        if (end >= content.length() || end < 0) {
            return content;
        }
        if (begin >= end) {
            return content;
        }
        String starStr = "";
        for (int i = begin; i < end; i++) {
            starStr = starStr + "*";
        }
        return content.substring(0, begin) + starStr + content.substring(end, content.length());

    }

    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content  传入的字符串
     * @param frontNum 保留前面字符的位数
     * @param endNum   保留后面字符的位数
     * @return 带星号的字符串
     */

    private String getStarString2(String content, int frontNum, int endNum) {

        if (frontNum >= content.length() || frontNum < 0) {
            return content;
        }
        if (endNum >= content.length() || endNum < 0) {
            return content;
        }
        if (frontNum + endNum >= content.length()) {
            return content;
        }
        String starStr = "";
        for (int i = 0; i < (content.length() - frontNum - endNum); i++) {
            starStr = starStr + "*";
        }
        return content.substring(0, frontNum) + starStr
                + content.substring(content.length() - endNum, content.length());
    }

    private SwipeRefreshListener mSwipeRefreshListener;

    public interface SwipeRefreshListener {
        void SwipeRefresh();
    }

    public void setSwipeRefreshLayoutStyls(SwipeRefreshLayout mSwipeRefreshLayout, SwipeRefreshListener swipeRefreshListener) {
        mSwipeRefreshListener = swipeRefreshListener;
        mSwipeRefreshLayout.setColorSchemeResources(
                R.color.blue,
                R.color.red,
                R.color.greenyellow,
                R.color.orange,
                R.color.fuchsia
        );
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeRefreshListener.SwipeRefresh();
            }
        });
    }

    /**
     * 判断Button是否可以点击
     *
     * @param views
     * @param btnSubmit
     * @return
     */
    public TextWatcher textWatcher(final ArrayList<TextView> views, final Button btnSubmit) {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                for (int i = 0; i < views.size(); i++) {
                    TextView view = views.get(i);
                    if (view.getText().toString().trim().length() == 0) {
                        btnSubmit.setBackgroundResource(R.drawable.btn_unselect);
                        btnSubmit.setEnabled(false);
                        return;
                    }
                }
                btnSubmit.setBackgroundResource(R.drawable.btn_select);
                btnSubmit.setEnabled(true);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
    }

    public String getJson(Context context, String fileName) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            InputStream open = assetManager.open(fileName);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            int ch = -1;
            byte[] buffer = new byte[1024 * 4];
            while ((ch = open.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, ch);

            }
            open.close();
            byteArrayOutputStream.close();
            return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    public List<Class> tlisTypeTokent(String body) {
        Gson gson = new Gson();
        Type types = new TypeToken<List<Class>>() {
        }.getType();
        List<Class> list = gson.fromJson(body, types);
        return list;
    }


    /**
     * 保存bitmap到本地
     *
     * @param bitmap
     * @return
     */
    public static void saveBitmap(Bitmap bitmap) {
        File filePic;
        String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
        savePath = savePath + "/NameImage.png";
        try {
            filePic = new File(savePath);
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    /**
     * 获取app存储目录
     *
     * @param context
     * @return
     */
    public static String getSdCardPath(Context context) {
        return Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName(context) + "/";
    }


    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized String getVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取图标 bitmap
     *
     * @param context
     */
    public static synchronized Bitmap getBitmap(Context context) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getApplicationContext()
                    .getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        Drawable d = packageManager.getApplicationIcon(applicationInfo); //xxx根据自己的情况获取drawable
        BitmapDrawable bd = (BitmapDrawable) d;
        Bitmap bm = bd.getBitmap();
        return bm;
    }

    /**
     * 安装APK
     *
     * @param
     * @return
     * @throws
     * @date
     */
    public static void install(Context context, String packName, String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri contentUri = FileProvider.getUriForFile(context, packName + ".fileProvider", new File(filePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }


    /**
     * 获取一段带颜色的文字
     *
     * @param text
     * @param color
     * @return
     */
    public static CharSequence getColorText(String text, int color) {
        SpannableStringBuilder style = new SpannableStringBuilder(text);
        style.setSpan(new ForegroundColorSpan(color), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return style;
    }


    /**
     * 获取一段设置大小的文字
     *
     * @param dp
     * @return
     */
    public static CharSequence getSizeText(String text, int dp) {
        SpannableString ss = new SpannableString(text);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(dp, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return new SpannedString(ss);
    }

    /**
     * 复制文本到系统剪切板
     */
    public static void copyTextToSystem(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", text);
        cm.setPrimaryClip(mClipData);
        Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 从系统剪切板获取文本
     */
    public static String getSystemCopyText(Context context) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        return cm.getPrimaryClip().toString();
    }

    /**
     * 将字符串的编码格式转换为utf-8
     *
     * @param str
     * @return Name = new
     * String(Name.getBytes("ISO-8859-1"), "utf-8");
     */
    public String toUTF8(String str) {
        if (isEmpty(str)) {
            return "";
        }
        try {
            if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
                str = new String(str.getBytes("GB2312"), "utf-8");
                return str;
            }
        } catch (Exception exception) {
        }
        try {
            if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
                str = new String(str.getBytes("ISO-8859-1"), "utf-8");
                return str;
            }
        } catch (Exception exception1) {
        }
        try {
            if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
                str = new String(str.getBytes("GBK"), "utf-8");
                return str;
            }
        } catch (Exception exception3) {
        }
        return str;
    }

    /**
     * 判断是否为空
     *
     * @param str
     * @return
     */
    public boolean isEmpty(String str) {
        // 如果字符串不为null，去除空格后值不与空字符串相等的话，证明字符串有实质性的内容
        if (str != null && !str.trim().isEmpty()) {
            return false;// 不为空
        }
        return true;// 为空
    }
}


